package cn.silky.demo;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.ui.freemarker.SpringTemplateLoader;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class PDFUtil {

    private static Configuration cfg = null;

    // 导出到指定 PDF 路径
    public static void exportPDF(String html, String pdf, String... fonts) throws DocumentException, IOException, TemplateException {
        ITextRenderer renderer = new ITextRenderer();
        addFont(renderer, fonts);
        try (OutputStream os = new FileOutputStream(pdf)) {
            renderer.setDocumentFromString(html);
            renderer.layout();
            renderer.createPDF(os);
        }
    }

    // 解析 FreeMarker 模板
    public static String parseFreemarker(String freemarker, Map<String, Object> dataModel) throws IOException, TemplateException {
        if (cfg == null) {
            cfg = initConfiguration();
        }
        Template temp = cfg.getTemplate(freemarker);
        try (Writer out = new StringWriter()) {
            temp.process(dataModel, out);
            return out.toString();
        }
    }

    // 加载准备好的字体
    private static void addFont(ITextRenderer renderer, String... fonts) throws DocumentException, IOException {
        ITextFontResolver fontResolver = renderer.getFontResolver();
        for (String font : fonts) {
            fontResolver.addFont(font, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        }
    }

    // 初始化 FreeMarker 配置
    private static Configuration initConfiguration() throws IOException {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);
        // 模板路径
        cfg.setTemplateLoader(new SpringTemplateLoader(new DefaultResourceLoader(), "classpath:/templates/"));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);
        cfg.setWrapUncheckedExceptions(true);
        return cfg;
    }

}